package com.langyiquan.front.websocket;

import com.langyiquan.enums.MsgActionEnum;
import com.langyiquan.utils.JsonUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;


public class MsgHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    // 用于记录和管理所有客户端的channle
    public static ChannelGroup users =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg)
            throws Exception {

        String content = msg.text();
        DataContent dataContent = JsonUtils.jsonToPojo(content, DataContent.class);
        Integer action = dataContent.getAction();

        Channel currentChannel = ctx.channel();

        // 1. 判断消息类型，根据不同的类型来处理不同的业务
        if (action == MsgActionEnum.MSG.type) {

            String message = dataContent.getMsg();
            DataContent dataContentMsg = new DataContent();
            dataContentMsg.setMsg(message);
            dataContentMsg.setAction(MsgActionEnum.MSG.type);

            // 发送消息
            for(Channel channel: users){
                channel.writeAndFlush(
                        new TextWebSocketFrame(
                                JsonUtils.objectToJson(dataContentMsg)));
            }

        }  else if (action == MsgActionEnum.KEEPALIVE.type) {
            System.out.println("收到来自channel为[" + currentChannel + "]的心跳包...");
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        users.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        users.remove(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
        users.remove(ctx.channel());
    }
}

